package com.mrjy.share.bo;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.mrjy.common.entity.ShareCodeInfo;
import com.mrjy.common.entity.ShareMemberInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.util.RandomUtil;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.share.dao.IShareCodeDao;
import com.mrjy.share.dao.IShareMemberDao;

@Service("shareCodeBo")
public class ShareCodeBo implements IShareCodeBo {
	
	@Resource
	private IShareCodeDao shareCodeDao;
	@Resource 
	private IUserInfoDao userInfoDao;
	@Resource 
	private IShareMemberDao shareMemberDao;

	@Override
	public int txInsert(UserInfo u) {
		List<ShareCodeInfo> scList=new ArrayList<ShareCodeInfo>();
		ShareCodeInfo qsc=new ShareCodeInfo();
		qsc.setUserId(u.getId());
		qsc.setCodeLevel(1);
		qsc.setStatus(1);
		if(shareCodeDao.countShareCdoeInfo(qsc)==0){
			qsc.setShareCode(u.getRecommendCode());
			scList.add(qsc);
		}
//		for(int i=0;i<6;i++){
//			ShareCodeInfo sc=new ShareCodeInfo();
//			sc.setShareCode(RandomUtil.generateString2(4));
//			sc.setUserId(u.getId());
//			sc.setCodeLevel(2);
//			scList.add(sc);
//		}
		
		//单一插入分享码
		ShareCodeInfo sc=new ShareCodeInfo();
		sc.setShareCode(RandomUtil.generateString2(6));
		sc.setUserId(u.getId());
		sc.setCodeLevel(2);
		sc.setStatus(0);
		scList.add(sc);
		
		boolean flag = true;
		int result = 0;
		while(flag){
			result= shareCodeDao.insertBatch(scList);
			if(result == 1){
				flag = false;
			}
		}
		return result;
	}
	@Override
	public int txBindUserInfo(ShareCodeInfo sc) {
		
		ShareCodeInfo qsc=shareCodeDao.queryById(sc.getId());
		UserInfo u=userInfoDao.queryByMobilePhone(sc.getMobilePhone());
		if(u.getRecommendCode()!=null){
			return 0;
		}
		UserInfo uui=new UserInfo();
		uui.setId(sc.getId());
		uui.setRecommendCode(qsc.getShareCode());
		userInfoDao.updateById(uui);
		
		return shareCodeDao.updateById(sc);
	}

	public List<ShareCodeInfo> queryShareCodeInfo(UserInfo u){
		ShareCodeInfo sc=new ShareCodeInfo();
		sc.setUserId(u.getId());
		return shareCodeDao.listShareCodeInfo(sc);
	}

	@Override
	public List<ShareCodeInfo> listMemberCountByShareCode(
			ShareCodeInfo shareCode) {
		// TODO Auto-generated method stub
		return null;
	}
	/**
	 *  检查是否被一级分销员邀请
	 */
	@Override
	public void isInvited(String mobilePhone, Map<String, Object> map) {
		ShareCodeInfo info = shareCodeDao.selectByMobilePhone(mobilePhone);
		if (null == info) { //没有信息， 则表明不是被一级分销推荐的
			map.put("err_code", -1);
			map.put("err_msg", "未被邀请");
		}else {
			if (info.getStatus() == 0) { //未处理邀请
				map.put("err_code", 0);
				map.put("err_msg", "被邀请，未处理邀请");
				map.put("shareCodeInfo", info);
			}else if(info.getStatus() == 1){// 接受邀请
				map.put("err_code", 1);
				map.put("err_msg", "已接受邀请");
			}else if (info.getStatus() == 2) { //拒绝邀请
				map.put("err_code", 2);
				map.put("err_msg", "拒绝邀请");
			}
		}
	}
	/**
	 * 更新被邀请的状态
	 */
	@Override
	public void txInvitedStatus(ShareCodeInfo info, Map<String, Object> map) {
		int flag = shareCodeDao.updateStatusByMobilePhone(info);
		if (flag > 0 ) {
			if (info.getStatus() == 1) {//同意邀请
				//手机号码是二级的，即被邀请的人，查询邀请码，此时的userId为一级分销员的id
				ShareCodeInfo shareCodeInfo = shareCodeDao.selectByMobilePhone(info.getMobilePhone());
				
				//1.更新userInfo表的share_level（分销等级）和recommend_code分享码自己的
				UserInfo userInfo = new UserInfo();
				userInfo.setId(info.getUserId());
				userInfo.setShareLevel(2);
				userInfo.setRecommendCode(shareCodeInfo.getShareCode());
				
				userInfoDao.updateById(userInfo);
				
				//2.插入记录到share_member_info表，userId为被推荐人，share_code为一级分销员的分享码
				//通过一级推荐人的userid 去shareCodeInfo 查询分享码，code_level=1 表示一级
				ShareCodeInfo temp = new ShareCodeInfo();
				temp.setUserId(shareCodeInfo.getUserId());
				temp.setCodeLevel(1);
				ShareCodeInfo sCodeInfo = shareCodeDao.queryUnshareCode(temp);
				ShareMemberInfo sMemberInfo = new ShareMemberInfo();
				sMemberInfo.setUserId(info.getUserId());//被推荐人
				sMemberInfo.setShareCode(sCodeInfo.getShareCode());//一级分销员的分享码
				sMemberInfo.setRegisterTime(new Date());
				
				shareMemberDao.insert(sMemberInfo);
			}
			map.put("err_code", 0);//更新成功
			map.put("err_msg", "更新成功");
		}else {
			map.put("err_code", -1);//更新异常
			map.put("err_msg", "更新异常");
		}
	}

	@Override
	public Object queryCountSecondary(ShareCodeInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		if(null == info.getCodeLevel()){
			info.setCodeLevel(2); //1 一级分销 ， 2二级分销
		}
		if(null == info.getStatus()){
			info.setStatus(1);// 0 默认 1 同意 2拒绝
		}
		
		List<ShareCodeInfo> infoList = shareCodeDao.queryCountSecondary(info);
		int total = shareCodeDao.countSecondary(info);
		map.put("rows", infoList);
		map.put("total", total);
		return map;
	}

	@Override
	public Object countAllByUserId(ShareCodeInfo info) {
		if(null == info.getCodeLevel()){
			info.setCodeLevel(2); //1 一级分销 ， 2二级分销
		}
		if(null == info.getStatus()){
			info.setStatus(1);// 0 默认 1 同意 2拒绝
		}
		int all = shareCodeDao.countAllByUserId(info);
		return all;
	}
	
	@Override
	public Object queryShareCodeDetail(ShareCodeInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		info.setCodeLevel(2);
		info.setStatus(0);
		ShareCodeInfo shareCodeInfo = shareCodeDao.queryUnshareCode(info);
		info.setStatus(null);
		System.out.println("====>"+info.getRows());
		List<ShareCodeInfo> list = shareCodeDao.queryCountSecondary(info);
		
		map.put("unshare", shareCodeInfo);
		map.put("shared", list);
		
		return map;
	}
	/**
	 *  查询二级分销员的详细信息，二级分销员主页信息
	 */
	@Override
	public void querySecondDetailInfo(ShareCodeInfo info, Map<String, Object> map) {
		ShareCodeInfo shareCodeInfo = shareCodeDao.selectByMobilePhone(info.getMobilePhone());
		if (null == shareCodeInfo) {
			map.put("err_code", -1);
			map.put("err_msg", "查询异常");
		}else {
			map.put("err_code", 0);
			map.put("err_msg", "");
			map.put("shareCodeInfo", shareCodeInfo);
		}
	}
	
	/**
	 *  发出邀请
	 */
	@Override
	public Object txSendInvited(ShareCodeInfo info) {
		Map<String , Object> map = new HashMap<String, Object>();
		//1.根据手机号码查询是否已经被邀请了
		ShareCodeInfo temp = new ShareCodeInfo();
		temp.setMobilePhone(info.getMobilePhone());
		ShareCodeInfo sci = shareCodeDao.selectByMobilePhone(info.getMobilePhone());
		if (null != sci) {
			map.put("err_code", -1);
			map.put("er_msg", "该用户已经被邀请");
			return map;
		}
		//2.检验用户和手机号是否存在于用户表
		UserInfo tempUser = new UserInfo();
		tempUser.setUserName(info.getUserName());
		tempUser.setMobilePhone(info.getMobilePhone());
		UserInfo userInfo = userInfoDao.selectByUserInfo(tempUser);
		if (null == userInfo) {
			map.put("er_code", -2);
			map.put("err_msg", "此用户还不是本平台会员，或者手机号码和姓名匹配不上");
			return map;
		}
		//3.根据分享码和userId查询数据
		ShareCodeInfo shareCodeInfo = shareCodeDao.queryByUserIdAndShareCode(info);
		if (null != shareCodeInfo) {
			if (StringUtils.isNotBlank(shareCodeInfo.getMobilePhone())) {
				map.put("err_code", 1);
				map.put("err_msg", "该分享码已被使用");
			}else {//更新数据
				int count = shareCodeDao.updateByUserIdAndShareCode(info);
				if (count > 0) {
					//如果插入成功，检查该一级分销员是否还有未使用的子分享码，如果有则不插入数据，如果没有，则新增新的数据
					int num = shareCodeDao.queryUnShareCodeCount(info);
					if (num == 0) {
						//单一插入分享码
						ShareCodeInfo sc=new ShareCodeInfo();
						sc.setShareCode(RandomUtil.generateString2(6));
						sc.setUserId(info.getUserId());
						sc.setCodeLevel(2);
						sc.setStatus(0);
						
						shareCodeDao.insert(sc);
					}
					
					map.put("err_code", 0);
					map.put("err_msg", "邀请成功");
				}else {
					map.put("err_code", 2);
					map.put("err_msg", "邀请失败");
				}
			}
			return map;
		}
		return map;
	}
	/**
	 * 查询一级分销员还没有分享的子分享码条数
	 * @author csshui
	 */
	@Override
	public int queryUnShareCodeCount(ShareCodeInfo info) {
		int count = shareCodeDao.queryUnShareCodeCount(info);
		return count;
	}
	@Override
	public Object queryUnshareCode(ShareCodeInfo info) {
		info.setCodeLevel(2);
		info.setStatus(0);
		ShareCodeInfo shareCodeInfo = shareCodeDao.queryUnshareCode(info);
		if(null == shareCodeInfo.getShareCode()){
			return "ok";// 表示可以继续插入新的子码
		}else{
			return "error";//表示不需要插入新的子码
		}
	}
	
	
	
	

}
